package com.dayuanit.dy17.library.controller;

import com.dayuanit.dy17.library.dto.ResponseDTO;
import com.dayuanit.dy17.library.entity.User;
import com.dayuanit.dy17.library.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    public UserController() {
        System.out.println("-------UserController()-----");
    }

    @RequestMapping(value = "/user/login.do")
    @ResponseBody
    public ResponseDTO login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        try {
            User user = userService.login(username, password);

            // 将用户信息保存在session中
            HttpSession session = req.getSession();
            session.setAttribute("loginUser", user);

            return ResponseDTO.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/user/logout.do")
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如果找不到session对象，就返回null
        HttpSession session = req.getSession(false);

        if (null != session) {
            session.invalidate();
        }

        resp.sendRedirect("/");
    }
}
